/**
 * Copyright (C) 2008 aileron.cc
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package cc.aileron.mail.sender.smtp;

import java.util.Properties;

import javax.mail.Session;
import javax.mail.internet.InternetAddress;

import cc.aileron.mail.sender.MailFrom;
import cc.aileron.mail.sender.MailSenderModule;

import com.google.inject.Provider;

/**
 * smtp-sender-module
 * 
 * @author Aileron
 * 
 */
public class SmtpSenderModule extends MailSenderModule
{
    /**
     * MailFromの生成
     * 
     * @return
     * @throws Exception
     */
    private MailFrom newFrom() throws Exception
    {
        final InternetAddress fromAddress;
        final Session session;

        fromAddress = new InternetAddress(account.fromAddress,
                account.fromAddress, setting.encoding);

        final Properties props = System.getProperties();
        props.put("mail.smtp.host", account.smtpHost);
        props.put("mail.smtp.localhost", account.localHost);
        session = Session.getDefaultInstance(props, null);

        return new MailFrom(session, fromAddress);
    }

    /*
     * (非 Javadoc)
     * 
     * @see cc.aileron.mail.sender.MailSenderModule#getMailFromProvider()
     */
    @Override
    protected Provider<MailFrom> getMailFromProvider()
    {
        return provider;
    }

    /**
     * constractor
     * 
     * @param account
     * 
     * @throws Exception
     */
    public SmtpSenderModule(final SmtpAccount account) throws Exception
    {
        this.account = account;

        final MailFrom from = newFrom();
        this.provider = new Provider<MailFrom>()
        {
            public MailFrom get()
            {
                return from;
            }
        };
    }

    /**
     * from
     */
    private final Provider<MailFrom> provider;

    /**
     * account
     */
    private final SmtpAccount account;
}
